/* BSD Socket API Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include <sys/param.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"

#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include "cJSON.h"
#include "udp.h"
#include "task_mag.h"

#define PORT 1000

static const char *TAG = "UDP Service";

int sock;
struct sockaddr_storage source_addr; // Large enough for both IPv4 or IPv6

static void udp_server_task(void *pvParameters)
{
    char rx_buffer[128];
    char addr_str[128];
    int addr_family = (int)pvParameters;
    int ip_protocol = 0;
    struct sockaddr_in6 dest_addr;

    memset(&source_addr, 0, sizeof(source_addr));
    while (1)
    {

        if (addr_family == AF_INET)
        {
            struct sockaddr_in *dest_addr_ip4 = (struct sockaddr_in *)&dest_addr;
            dest_addr_ip4->sin_addr.s_addr = htonl(INADDR_ANY);
            dest_addr_ip4->sin_family = AF_INET;
            dest_addr_ip4->sin_port = htons(PORT);
            ip_protocol = IPPROTO_IP;
        }
        else if (addr_family == AF_INET6)
        {
            bzero(&dest_addr.sin6_addr.un, sizeof(dest_addr.sin6_addr.un));
            dest_addr.sin6_family = AF_INET6;
            dest_addr.sin6_port = htons(PORT);
            ip_protocol = IPPROTO_IPV6;
        }

        sock = socket(addr_family, SOCK_DGRAM, ip_protocol);
        if (sock < 0)
        {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket created");

#if defined(CONFIG_EXAMPLE_IPV4) && defined(CONFIG_EXAMPLE_IPV6)
        if (addr_family == AF_INET6)
        {
            // Note that by default IPV6 binds to both protocols, it is must be disabled
            // if both protocols used at the same time (used in CI)
            int opt = 1;
            setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
        }
#endif

        int err = bind(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (err < 0)
        {
            ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
        }
        ESP_LOGI(TAG, "Socket bound, port %d", PORT);

        while (1)
        {
#if 0
            ESP_LOGI(TAG, "Waiting for data");
#endif

            socklen_t socklen = sizeof(source_addr);
            int len = recvfrom(sock, rx_buffer, sizeof(rx_buffer) - 1, 0, (struct sockaddr *)&source_addr, &socklen);

            // Error occurred during receiving
            if (len < 0)
            {
                ESP_LOGE(TAG, "recvfrom failed: errno %d", errno);
                break;
            }
            // Data received
            else
            {
                // Get the sender's ip address as string
                if (source_addr.ss_family == PF_INET)
                {
                    inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);
                }
                else if (source_addr.ss_family == PF_INET6)
                {
                    inet6_ntoa_r(((struct sockaddr_in6 *)&source_addr)->sin6_addr, addr_str, sizeof(addr_str) - 1);
                }

                rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string...

                /**
                 * @brief 处理收到的数据
                 *
                 */
                udp_data_handle(rx_buffer);
#if 0
                int err = sendto(sock, rx_buffer, len, 0, (struct sockaddr *)&source_addr, sizeof(source_addr));
                if (err < 0)
                {
                    ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
                    break;
                }
#endif
            }
        }

        if (sock != -1)
        {
            ESP_LOGE(TAG, "Shutting down socket and restarting...");
            shutdown(sock, 0);
            close(sock);
        }
    }
    vTaskDelete(NULL);
}

/**
 * @brief udp数据接收处理
 *
 * @param data
 */
void udp_data_handle(char *data)
{
    char key;

    cJSON *json, *json_key1;

    json = cJSON_Parse(data);
    if (json)
    {
        json_key1 = cJSON_GetObjectItem(json, "key");
        if (json_key1)
        {
            key = *cJSON_GetStringValue(json_key1);
            ESP_LOGI(TAG, "读取到键值 %c", key);

            /**
             * @brief 发送键值到页面
             *
             */
            udp_keyboard_sned_key(key);
        }

        cJSON_Delete(json);
    }
}

xQueueHandle udp_send_queue;

/**
 * @brief udp发送服务
 *
 * @param pvParameters
 */
static void udp_send_server_task(void *pvParameters)
{
    char buf[UDP_SEND_QUEUE_LEN];
    while (1)
    {
        if (xQueueReceive(udp_send_queue, (void *)buf, portMAX_DELAY))
        {
            ESP_LOGE(TAG, "UDP发送字符串 %s", buf);

            if (sock >= 0)
            {
                if (source_addr.ss_family == PF_INET)
                {
                    int err = sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&source_addr, sizeof(source_addr));
                    if (err < 0)
                    {
                        ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
                        break;
                    }
                }
            }
        }
    }
}

/**
 * @brief 初始化udp
 *
 */
void udp_com_init(void)
{
    static uint32_t init = false;

    if (init == false)
    {
        init = true;

        ESP_LOGE(TAG, "启动接收UDP服务");
        xTaskCreate(udp_server_task, "udp_server", 4096, (void *)AF_INET, 5, NULL);

        ESP_LOGE(TAG, "启动发送UDP服务");
        udp_send_queue = xQueueCreate(1, sizeof(char) * UDP_SEND_QUEUE_LEN);
        xTaskCreate(udp_send_server_task, "udp_send_server_task", 4096, (void *)AF_INET, 5, NULL);
    }
}
